package com.yww.leetcode.binarytree;

import com.yww.leetcode.common.TreeNode;

import java.nio.IntBuffer;
import java.util.LinkedList;
import java.util.Random;

/**
 * @author yww
 * @description 104. 二叉树的最大深度
 * @since 2024/2/8 17:26
 */
public class MaxDepth104 {
    // 二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。
    public int maxDepth(TreeNode root) {
        Random random = new Random();
        int randomInt = random.nextInt();
        if (randomInt % 2 == 0) {
            return postOrder(root); // 后序遍历进行计算
        } else {
            randomInt = random.nextInt();
            if (randomInt % 2 == 0) {
                return traversal(root); // 迭代遍历进行计算
            } else {
                return level(root); // 层序遍历进行计算
            }
        }
    }

    /**
     * 层序遍历
     */
    private int level(TreeNode root) {
        if (root == null) {
            return 0;
        }
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int maxDepth = 0;
        while (!queue.isEmpty()) {
            maxDepth++;
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode poll = queue.poll();
                if (poll.left != null) {
                    queue.offer(poll.left);
                }
                if (poll.right != null) {
                    queue.offer(poll.right);
                }
            }
        }
        return maxDepth;
    }

    /**
     * 迭代遍历
     */
    private int traversal(TreeNode root) {
        if (root == null) {
            return 0;
        }
        TreeNode cur = root;
        TreeNode poped = null;
        LinkedList<TreeNode> stack = new LinkedList<>();
        int maxDepth = 0;
        while (cur != null || !stack.isEmpty()) {
            if (cur != null) {
                stack.push(cur);
                int size = stack.size();
                if (size > maxDepth) {
                    maxDepth = size; // 栈的最大size就是最大深度
                }
                cur = cur.left;
            } else {
                TreeNode peek = stack.peek();
                if (peek.right == null || peek.right == poped) {
                    poped = stack.pop();
                } else {
                    cur = peek.right;
                }
            }
        }
        return maxDepth;
    }

    /**
     * 使用后序遍历进行计算
     **/
    private int postOrder(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftDepth = postOrder(root.left); // 左递归
        int rightDepth = postOrder(root.right); // 右递归
        return Math.max(leftDepth, rightDepth) + 1; // 后
    }


}
